#include <iostream>
#include <assert.h>
#include <tws_debugging.h>
#include <xinifile.h>
#include <qbytearray.h>
#include "xinfomatlayouttypeparser.h"

#define _DEBUGING_LAYOUT_

const char INI_SECTION[] = "";
const char INI_KEY[] = "Boot_Layout";
const char DEFAULT_INI_FILE[] = "/usr/infomat/boot.conf";

XInfomatLayoutTypeParser::XInfomatLayoutTypeParser() :
    m_result(INFOMAT_RESULT_OK)
{
}

XInfomatLayoutTypeParser::~XInfomatLayoutTypeParser()
{
	DEBUG("[Layout Type Parser]: Cleaning Up ... ");
}

void XInfomatLayoutTypeParser::getResource(QByteArray in_datagram)
{
    char* data = new char[in_datagram.size()];
    memcpy(data, in_datagram.data(), in_datagram.size());
    assert(INFOMAT_CONFIG_PROTOCOL == *data);

    STInfomatLayoutType *tmpdata = reinterpret_cast<STInfomatLayoutType*> (data);
	memcpy(&m_layoutType, tmpdata, in_datagram.size());
	tmpdata = NULL;

	if (NULL!=data)
	{
		delete data;
		data = NULL;
	}

#ifdef _DEBUGING_LAYOUT_
    DEBUG("MacType checking ...");
    DEBUG("Pass in Data, After Conversion");
    DEBUG("totoal data size:\t\t%d", in_datagram.size());
    DEBUG("protocol : %x", m_layoutType.head.protocol);
    DEBUG("type     : %d", m_layoutType.head.type);
    DEBUG("size     : %d", m_layoutType.head.size);
    DEBUG("result   : %d", m_layoutType.head.result);
    DEBUG("command  : %d", m_layoutType.head.command);
    DEBUG("mac      : %d", m_layoutType.layoutNo);
#endif

    m_layoutType.head.result = INFOMAT_RESULT_OK; //initialized

    switch (m_layoutType.head.command)
    {
        case INFOMAT_COMMAND_READ:
            read();
            break;

        case INFOMAT_COMMAND_WRITE:
            write();
            break;

        default:
            DEBUG("XMacTypeParser: no such command");
            m_result = INFOMAT_RESULT_ERR;
            break;
    }

    return;
}

void XInfomatLayoutTypeParser::read()
{
    XIniFile iniFile;

    assert(0 == iniFile.open(DEFAULT_INI_FILE));

    int keyValue;
    if (0 != iniFile.readInt(INI_SECTION, INI_KEY, keyValue))
        m_result = INFOMAT_RESULT_ERR;

    iniFile.close();
    m_layoutType.layoutNo = (uint8_t)(keyValue);

#ifdef _DEBUGING_LAYOUT_
    DEBUG("Read udpd.conf file .... [OK]");
    DEBUG("Boot_Layout ini: %02x\t\t\t [OK]", m_layoutType.layoutNo);
#endif
    return;
}

void XInfomatLayoutTypeParser::write()
{
    XIniFile iniFile;
    assert(0 == iniFile.open(DEFAULT_INI_FILE, EIniReadWrite));

    if (0 != iniFile.writeInt(INI_SECTION, INI_KEY, int(m_layoutType.layoutNo)))
        m_result = INFOMAT_RESULT_ERR;

    iniFile.flush();
    return;
}

QByteArray XInfomatLayoutTypeParser::getOutDatagram()
{
    m_layoutType.head.result = m_result;
    char* tmpdata = reinterpret_cast<char*> (&m_layoutType);
	QByteArray outdata = QByteArray(tmpdata, sizeof (m_layoutType));
	return outdata;
}

